package com.maybach.web.controller.partner;

import com.audi.dubbo.api.admin.models.AdminModel;
import com.maybach.common.BizResult;
import com.maybach.common.model.PartnerDO;
import com.maybach.component.city.CityData;
import com.maybach.component.city.domain.Province;
import com.maybach.core.ao.PartnerAO;
import com.maybach.core.dubbo.consumer.adapter.AdminServiceDubooAdapter;
import com.maybach.core.form.partner.PartnerForm;
import com.maybach.core.form.partner.PartnerQueryForm;
import com.maybach.util.StringUtil;
import com.maybach.util.query.support.PageResult;
import com.maybach.web.constants.WebConstants;
import com.maybach.web.framework.util.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/partner/")
public class PartnerController {
    @Autowired
    protected PartnerAO partnerAO;
    @Autowired
    private AdminServiceDubooAdapter adminServiceDubooAdapter;
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    /**
     * 添加页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "add")
    public String add(@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (!model.containsAttribute("partnerForm")) {
            PartnerForm partnerForm = new PartnerForm();
            model.addAttribute(partnerForm);
        }
        // 获取业务经理

        Map<String, String> map =  getUsersByDubbo("b2bManager");

        model.addAttribute("admin", map);
        return "partner/add";
    }

    /**
     * 关闭订单
     */
    @RequiresAuthentication
    @RequestMapping(value = "closeOrder")
    public String closeOrder() {

        return "partner/closeOrder";
    }

    /**
     * 操作记录
     */
    @RequiresAuthentication
    @RequestMapping(value = "orderActLog")
    public String orderActLog() {

        return "partner/orderActLog";
    }

    /**
     * 添加partner
     *
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doAdd", method = RequestMethod.POST)
    public String doAdd(@Valid PartnerForm partnerForm, BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        // 判断公司是否存在
        if (StringUtils.isNotBlank(partnerForm.getCertificateCode())&& this.partnerAO.isPartnerExist(partnerForm.getCertificateCode())) {
            bindingResult.addError(new FieldError("partnerForm", "certificateCode", "对应的公司已存在"));
        }

        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            processProvice(partnerForm);
            Long partnerId = partnerAO.addPartner(partnerForm);
            logger.debug("add partner partnerId={}", partnerId);

        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }

        return "result";
    }


    /**
     * 编辑页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "edit")
    public String edit(@RequestParam(value = "id") Long id, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (!model.containsAttribute("partnerForm")) {
            PartnerForm partnerForm = partnerAO.getPartnerForm(id);
            if (null == partnerForm) {
                partnerForm = new PartnerForm();
            }
            model.addAttribute(partnerForm);
        }
        // 获取业务经理

        Map<String, String> map =  getUsersByDubbo("b2bManager");

        model.addAttribute("admin", map);
        return "partner/add";
    }


    private Map<String,String> getUsersByDubbo(String role){
        List<AdminModel> list = adminServiceDubooAdapter.getAdminModelByRoleCode(role);

        Map<String, String> map = new HashMap<String, String>();
        for(AdminModel model : list){
            map.put(model.getAdminId()+"", getName(model));
        }
        return map;
    }

    private String getName(AdminModel model){
        if(StringUtil.isNotBlank(model.getExtattr())){
            return model.getExtattr();
        }
        return model.getNick();
    }

    /**
     * 添加partner
     *
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doUpdate", method = RequestMethod.POST)
    public String doUpdate(@Valid PartnerForm partnerForm, BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        if (partnerAO.isAnotherPartnerExist(partnerForm.getCertificateCode(), partnerForm.getId())) {
            bindingResult.addError(new FieldError("partnerForm", "certificateCode", "对应的公司已存在"));
        }
        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            processProvice(partnerForm);
            partnerAO.updatePartner(partnerForm);
            logger.debug("update partner partnerId={}", partnerForm.getId());
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }


        return "result";
    }

    /**
     * 处理无效省份和直辖市
     * @param partnerForm
     */
    private void processProvice(PartnerForm partnerForm) {
        if(null != partnerForm.getProviceId()){
            Province province = CityData.getProvinceById(partnerForm.getCityId());
            if(null == province){
                partnerForm.setProviceId(null);
                partnerForm.setCityId(null);
            }else{
                if(province.getRemark().equals("直辖市")){
                    partnerForm.setCityId(null);
                }
            }
        }
    }


    /**
     * 列表页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "list")
    public String list(@Valid PartnerQueryForm partnerQueryForm, BindingResult bindingResult, ModelMap model) {
        //model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (null == partnerQueryForm) {
            partnerQueryForm = new PartnerQueryForm();
        }
        if (!model.containsAttribute("partnerQueryForm")) {
            model.addAttribute(partnerQueryForm);
        }

        PageResult<PartnerDO> result = partnerAO.queryPartner(partnerQueryForm);
        model.addAttribute("pageResult", result);
        return "partner/list";
    }


    @ResponseBody
    @RequiresAuthentication
    @RequestMapping(value = "doUpdateStatus.json")
    public BizResult doUpdateStatus(@RequestParam(value = "status") Integer status, @RequestParam(value = "id") Long id) {
        return partnerAO.updatePartnerStatus(id, status);
    }


}